import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_app_update/flutter_app_update.dart';
import 'package:flutter_app_update/result_model.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:azring/entity/app_version_entity.dart';
import 'package:package_info_plus/package_info_plus.dart';

class VersionController extends GetxController {
  String? currentVersion;

  static VersionController get to => Get.find();

  @override
  void onInit() {
    super.onInit();

    _initPageInfo();
    AzhonAppUpdate.listener((ResultModel model) {
      debugPrint('$model');
    });
  }

  Future<void> _initPageInfo() async {
    final PackageInfo packageInfo = await PackageInfo.fromPlatform();
    currentVersion = packageInfo.version;
    print("当前版本：$currentVersion");
    requestVersion(true);
  }

  //判断version大小
  Future<void> requestVersion(bool isShowToast) async {
    final platform = GetPlatform.isAndroid ? '1' : '2';
    try {
      final response = await DefaultApi()
          .ringAppVersionQueryPlatformGet<Map<String, dynamic>>(
              platform: platform);

      if (response == null) {
        if (isShowToast) Toast.show("获取版本信息失败");
        return;
      }

      final entity = AppVersionEntity.fromJson(response);
      print("版本：-----$entity");

      // 检查数据是否存在
      if (entity.data == null) {
        if (isShowToast) Toast.show("版本信息为空");
        return;
      }

      // 测试用，可以取消注释
      // entity.data?.version = '0.0.10';
      // entity.data?.mustRenew = 0;
      // entity.data?.downUrl = "https://example.com/app.apk";

      bool isUpdate = false;
      if (entity.data?.version != null && currentVersion?.isNotEmpty == true) {
        List<int> newVersion =
            entity.data!.version!.split('.').map(int.parse).toList();

        List<int> version = currentVersion!.split('.').map(int.parse).toList();
        int maxLength = max(newVersion.length, version.length);
        for (var index = 0; index < maxLength; index++) {
          int newVersionPart =
              index < newVersion.length ? newVersion[index] : 0;
          int versionPart = index < version.length ? version[index] : 0;
          if (newVersionPart != versionPart) {
            isUpdate = newVersionPart > versionPart;
            break;
          }
        }
      }

      if (isUpdate) {
        showUpdateDialog(entity.data!);
      } else if (isShowToast) {
        Toast.show("已是最新版本");
      }
    } catch (e) {
      print("版本检查失败: $e");
      if (isShowToast) Toast.show("获取版本信息失败");
    }
  }

  @override
  void onClose() {
    super.onClose();
    AzhonAppUpdate.dispose();
  }

  showUpdateDialog(AppVersionData data) {
    final bool forcedUpgrade = data.mustRenew == 1;
    showDialog(
      context: Get.context!,
      barrierDismissible: !forcedUpgrade,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () => Future.value(!forcedUpgrade),
          child: AlertDialog(
            title: Text("新版本"),
            content: Text(data.describe ?? ''),
            actions: <Widget>[
              if (!forcedUpgrade)
                TextButton(
                  child: Text("取消"),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              TextButton(
                child: Text("更新"),
                onPressed: () {
                  _appUpdate(data);
                  if (!forcedUpgrade) {
                    Navigator.of(context).pop();
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  _appUpdate(AppVersionData data) {
    print("data-----------$data");
    if (data.downUrl?.isURL == true) {
      UpdateModel model = UpdateModel(
        data.downUrl!,
        "azringUpdate.apk",
        "ic_launcher",
        data.downUrl!,
      );
      AzhonAppUpdate.update(model);
    } else {
      Get.back(); // 关闭弹窗
      Toast.show("下载失败");
    }
  }
}
